<template>
  <div id="rtcPlayer">
    <video :id="webRtcPlayerBox" :muted="!isNotMute" autoplay style="width: 100%; height: auto; text-align:left;">
      Your browser is too old which doesn't support HTML5 video.
    </video>
    <div class="buttons-box" id="buttonsBox">
      <div class="buttons-box-left">
        <i v-if="!playing" class="iconfont icon-play jessibuca-btn" @click="playBtnClick"></i>
        <i v-if="playing" class="iconfont icon-pause jessibuca-btn" @click="pause"></i>
        <i class="iconfont icon-stop jessibuca-btn" @click="destroy"></i>
        <i v-if="isNotMute" class="iconfont icon-audio-high jessibuca-btn" @click="mute()"></i>
        <i v-if="!isNotMute" class="iconfont icon-audio-mute jessibuca-btn" @click="cancelMute()"></i>
      </div>
      <div class="buttons-box-right">
        <!--        <span class="jessibuca-btn">{{ kBps }} kb/s</span>-->
        <i class="iconfont icon-camera1196054easyiconnet jessibuca-btn" @click="screenshot"
           style="font-size: 1rem !important"></i>
        <i class="iconfont icon-shuaxin11 jessibuca-btn" @click="playBtnClick"></i>
        <i v-if="!fullscreen" class="iconfont icon-weibiaoti10 jessibuca-btn" @click="fullscreenSwich"></i>
        <i v-if="fullscreen" class="iconfont icon-weibiaoti11 jessibuca-btn" @click="fullscreenSwich"></i>
      </div>
    </div>
  </div>
</template>

<script>
import ZLMRTCClient from "@/assets/js/ZLMRTCClient";

let webrtcPlayer = null;

export default {
  name: 'rtcPlayer',
  data() {
    return {
      timer: null,
      playing: false,
      isNotMute: false,
      fullscreen: false,
      kBps: 0,
    };
  },
  props: {
    videoUrl: String,
    error: Function,
    hasaudio: Boolean,
    webRtcPlayerBox: String,
  },
  mounted() {
    let paramUrl = decodeURIComponent(this.$route.params.url);
    this.$nextTick(() => {
      if (typeof (this.videoUrl) === "undefined") {
        this.videoUrl = paramUrl;
      }
      console.log("初始化时的地址为: " + this.videoUrl);
      this.play(this.videoUrl);
    });
  },
  watch: {
    videoUrl: {
      handler(newData, oldData) {
        if (newData !== oldData) {
          this.pause();
          this.play(newData);
        }
      },
    },
  },
  methods: {
    play(url) {
      webrtcPlayer = new ZLMRTCClient.Endpoint({
        element: document.getElementById(this.webRtcPlayerBox), // video 标签
        debug: true, // 是否打印日志
        zlmsdpUrl: url, // 流地址
        simulecast: false,
        useCamera: false,
        audioEnable: true,
        videoEnable: true,
        recvOnly: true,
        usedatachannel: false,
      });

      webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR, (e) => { // ICE 协商出错
        console.error('ICE 协商出错');
        this.playing = false;
        this.eventcallbacK("ICE ERROR", "ICE 协商出错");
      });

      webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS, (e) => { // 获取到了远端流，可以播放
        console.log('播放成功', e.streams);
        this.playing = true;
        this.eventcallbacK("playing", "播放成功");
      });

      webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, (e) => { // offer anwser 交换失败
        this.playing = false;
        console.error('offer anwser 交换失败', e);
        this.eventcallbacK("OFFER ANSWER ERROR ", "offer anwser 交换失败");
        if (e.code === -400 && e.msg === "流不存在") {
          console.log("流不存在");
          this.timer = setTimeout(() => {
            webrtcPlayer.close();
            this.play(url);
          }, 100);
        }
      });

      webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_LOCAL_STREAM, (s) => { // 获取到了本地流
        this.eventcallbacK("LOCAL STREAM", "获取到了本地流");
      });
    },
    pause() {
      if (webrtcPlayer) {
        webrtcPlayer.close();
        webrtcPlayer = null;
      }
      console.log("pause");
      this.playing = false;
    },
    destroy() {
      this.pause();
      this.$emit('destroy', this.webRtcPlayerBox);
    },
    mute() {
      const video = document.getElementById(this.webRtcPlayerBox);
      if (video) {
        video.muted = true; // 设置视频静音
      }
      this.isNotMute = false;
    },
    cancelMute() {
      const video = document.getElementById(this.webRtcPlayerBox);
      if (video) {
        video.muted = false; // 取消视频静音
      }
      this.isNotMute = true;
    },
    playBtnClick() {
      if (this.playing) {
        this.pause();
      } else {
        this.play(this.videoUrl);
      }
    },
    fullscreenSwich() {
      this.fullscreen = !this.fullscreen;
      if (this.fullscreen) {
        this.enterFullscreen();
      } else {
        this.exitFullscreen();
      }
    },
    enterFullscreen() {
      const videoElement = document.getElementById(this.webRtcPlayerBox);
      if (videoElement.requestFullscreen) {
        videoElement.requestFullscreen();
      } else if (videoElement.mozRequestFullScreen) { // Firefox
        videoElement.mozRequestFullScreen();
      } else if (videoElement.webkitRequestFullscreen) { // Chrome, Safari and Opera
        videoElement.webkitRequestFullscreen();
      } else if (videoElement.msRequestFullscreen) { // IE/Edge
        videoElement.msRequestFullscreen();
      }
    },
    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) { // Firefox
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) { // IE/Edge
        document.msExitFullscreen();
      }
    },
    eventcallbacK(type, message) {
      console.log("player 事件回调");
      console.log(type);
      console.log(message);
      if (this.error && typeof this.error === 'function') {
        this.error(type, message);
      }
    },
    screenshot() {
      const video = document.getElementById(this.webRtcPlayerBox);
      const canvas = document.createElement('canvas'); // 创建一个临时的 canvas

      if (video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

        // 将 canvas 内容转换为图片 URL
        const screenshotUrl = canvas.toDataURL('image/png');

        // 创建一个隐藏的链接元素并触发下载
        const link = document.createElement('a');
        link.href = screenshotUrl;
        link.download = 'screenshot.png'; // 下载文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
        alert('视频尚未准备好');
      }
    },
  },
  destroyed() {
    clearTimeout(this.timer);
    this.pause();
  },
};
</script>

<style scoped>
.LodingTitle {
  min-width: 70px;
}

#rtcPlayer {
  width: 100%;
  position: relative;
  overflow: hidden;
}

#rtcPlayer video {
  width: 100%;
  height: auto;
  object-fit: contain;
}

.buttons-box {
  width: 100%;
  height: 28px;
  background-color: rgba(43, 51, 63, 0.7);
  position: absolute;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  left: 0;
  bottom: 0;
  user-select: none;
  z-index: 10;
}

.jessibuca-btn {
  width: 20px;
  color: rgb(255, 255, 255);
  line-height: 27px;
  margin: 0px 10px;
  padding: 0px 2px;
  cursor: pointer;
  text-align: center;
  font-size: 0.8rem !important;
}

.buttons-box-right {
  position: absolute;
  right: 0;
}
</style>
